package com.zzyl.generator;

import com.zzyl.common.constant.Constants;
import com.zzyl.generator.domain.ClassField;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class VelocityDemo {
    public static void main(String[] args) throws IOException {
        Properties p = new Properties();
        // velocity资源加载器，告诉模板引擎到类路径下寻找资源（比如模板）
        p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
        // 初始化velocity引擎
        Velocity.init(p);

        // 数据准备
        //实体类的字段
        List<ClassField> fieldList = new ArrayList<>();
        fieldList.add(new ClassField("Long", "id"));
        fieldList.add(new ClassField("String", "name"));
        fieldList.add(new ClassField("Integer", "age"));

        String packageName = "com.itheima.pojo";
        String className = "Student";

        VelocityContext context = new VelocityContext();
        // key: 要与模板中的变量名一致 $变量名
        context.put("packageName", packageName);
        context.put("className", className);
        context.put("fieldList", fieldList);

        //获取模板，resources下的模板文件
        Template template = Velocity.getTemplate("vm/pojo.java.vm");

        //填充数据
        FileWriter fileWriter = new FileWriter("G:\\Student.java");
        template.merge(context, fileWriter);
        //关闭流
        fileWriter.close();
    }
}
